﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Torch_Repository
{
    /// <summary>
    /// 用户表
    /// </summary>
    public class UsersDal : BaseDal<User>, IUsersDal
    {
        private SmartSchoolDbContext _dbcontext;
        private IUsersInfoDal _usersInfoDal;
        private ITeachPermissionDal _teachPermissionDal;
        private IStaffSalaryDal _staffSalaryDal;
        public UsersDal(SmartSchoolDbContext dbcontext, IUsersInfoDal usersInfoDal, ITeachPermissionDal teachPermissionDal) : base(dbcontext)
        {
            _usersInfoDal = usersInfoDal;
            _teachPermissionDal = teachPermissionDal;
        }

        public override async Task<int> DeleteAsync(User entity, bool isSaved = true) 
        {
            var result = 0;
            using (IDbContextTransaction _tran = _dbcontext.Database.BeginTransaction())
            {
                try
                {
                    _dbcontext.Entry(entity).State = EntityState.Deleted;
                    var UsInfoData = await _usersInfoDal.QueryAsync(user => user.Id == entity.Id);
                    var TeachData = _teachPermissionDal.QueryAsync(teach => teach.Id == entity.Id);
                    var Sum = 0;
                    if (UsInfoData != null)
                    {
                        foreach (var i in UsInfoData)
                        {
                            await _usersInfoDal.DeleteAsync(i);
                            //await _teachPermissionDal.DeleteAsync(i);
                            Sum += 1;
                        }
                    }
                    else 
                    {
                        return result;
                    }

                    if (Sum == UsInfoData.Count)
                    {
                        result = await _dbcontext.SaveChangesAsync();
                        if (result < 0)
                        {
                            _tran.Rollback();
                            result = 0;
                        }
                        else
                        {
                            _tran.Commit();
                        }
                    }
                    else
                    {
                        _tran.Rollback();
                    }

                }
                catch (Exception)
                {

                    _tran.Rollback();
                }

                return result;
            }
        }

    }
}
